import FormApi from "@/api/modules/form/formApi";
import Util from "@/js/Util.js"
import BpmInstApi from "../../../../../api/rxBpm/bpmInst";
import FormSolutionApi from "../../../../../api/rxBpm/formSolution"
import PublicApi from "@/api/public";
import rxAjax from '@/assets/ajax.js';
import Dialog from "@/js/Dialog";
import ButtonShow from "./ButtonShow";
import TokenUtil from "@/common/TokenUtil";

export default {
    data() {
        return {
            //表单方案按钮
            buttons: [],
            canStartFlow: false,
            //根实例
            rootVm: true,
            needConfirmDlg: false,
            processConfig: {
                buttons: [],
                startConfirm: false,
                fillOpinion: false,
                assignFlowUsers: false,
                assignBatchFlowUsers: false,
                startCalFlowusers: false,
                //是否允许选择路径。
                allowSelectPath: false,

                formType: "online"
            },
        }
    },
    computed: {
        rxForms() {
            return this.$refs.RxForm;
        }
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formSolutionLang",key);
        },
        i18n_(name,text,key){
            return this.$ti18(name,text,"detailButtonLang.taskButton",key);
        },
        //获取渲染表单对象
        getFormVm() {
            return this.$refs.RxForm;
        },
        /**
         * 处理按钮事件。
         * @param {Object}  btn     按钮对象。
         * @returns {Promise<void>}
         */
        async handMethod(btn) {
            let formBuild = this.getFormVm();
            this.buttonLoading = {
                key:btn.method,
                loading:true,
            }
            var res=await FormSolutionApi.validPreByButton(btn.preCondConfig,JSON.stringify(formBuild.data));
            this.buttonLoading = {
                key:'',
                loading:false,
            }
            if(!res.success){
                uni.showToast({
                    title: res.message, duration: 2000, icon: 'none'
                });
                return;
            }
            //表单方法
            if (btn.type == "formMethod") {
                let method = btn.method;
                if (formBuild && formBuild[method]) {
                    formBuild[method](this, btn);
                }
                return;
            }
            //自定义方法
            else if (btn.type == "custom") {
                let formJson = formBuild.data;
                let config = btn.config;
                let func = new Function("formJson", "rxAjax", "btn", config.action).bind(this);
                func(formJson, rxAjax, btn);
                return;
            }
            //调用预定义方法。
            if (this[btn.method]) {
                let methodList = ['submit','startFlow'];
                if(methodList.includes(btn.method)){
                    this.buttonLoading = {
                        key:btn.method,
                        loading:true,
                    }
                }
                this[btn.method](btn);
                return
            } else {
                uni.showToast({
                    title: `${btn.method},`+this.i18n('NotDefined','还没有定义!'), duration: 2000, icon: 'none'
                });
            }
        },
        /**
         * 计算按钮
         * @param {Object}  res 表单返回数据
         * @returns {*[]}
         */
        getButtons(res) {
            let buttons = [];
            let canSave = res.canSave;
            let readonly = this.action == 'detail';
            let pkId=res.data ? res.data[res.idField || "ID_"] : "";
            let instStatus=res.data ?res.data.INST_STATUS_: "";
            this.canStartFlow=res.canStartFlow;
            let flowInstId=res.data ? res.data.INST_ID_: "";
            let localDefId=res.formSolution.flowDefId;
            let context={
                canStartFlow:this.canStartFlow,
                instId:flowInstId,
                bpmDefId:localDefId,
                instStatus:instStatus,
                pkId: pkId,
                formSolution:res.formSolution
            }
            let btns = res.buttons ? JSON.parse(res.buttons) : [];
            for (let i = 0; i < btns.length; i++) {
                let btn = btns[i];
                if(btn.method=="print"){
                    continue;
                }
                if(btn.type=="edit" && context.instId){
                    //编辑
                    continue;
                }else if(readonly && btn.mode && btn.modeConfig.indexOf("detail")==-1){
                    //明细
                    continue;
                }
                else if(btn.type=="flowImage" && !context.bpmDefId && !context.instId){
                    //流程图 未配置流程时不显示
                    continue;
                }
                else if(btn.method=="startFlow" && !context.canStartFlow){
                    //启动流程
                    continue;
                }
                else if(["newSubmit","submit"].includes(btn.method) && !canSave){
                    //提交按钮
                    continue;
                }
                /**
                 * 判断按钮是否可以显示。
                 */
                if(ButtonShow[btn.method]){
                    let show=ButtonShow[btn.method](context);
                    if(!show){
                        continue;
                    }
                }
                btn.loading = false;
                buttons.push(btn);
            }
            if(instStatus){
                buttons.push({
                    id:'approvalHistory',
                    method:'approvalHistory',
                    style:false,
                    name:this.i18n_('approvalHistory','审批历史'),
                })
            }
            return buttons;
        },
        async initProcessConfig() {
            let self_ = this;
            await BpmInstApi.getProcessConfig(this.flowDefId).then(res => {
                if (!res.success) {
                    this.$message.warning(res.message);
                    return;
                }
                if (res.data) {
                    var config = Util.deepClone(self_.processConfig);
                    let buttonConfigs = [];
                    for (let i = 0; i < res.data.buttonConfigs.length; i++) {
                        //启动去除特送按钮
                        if (res.data.buttonConfigs[i].type != "specialDelivery") {
                            buttonConfigs.push(res.data.buttonConfigs[i]);
                        }
                    }
                    res.data.buttonConfigs = buttonConfigs;
                    self_.processConfig = Object.assign(config, res.data);
                }
            })
        },
        async ureportPrint(btn) {
            let json = this.rxForms.data;
            if (!json.ID_) {
                let title =this.i18n('useUreport','编辑状态才能使用报表!!');
                uni.showToast({
                    title: title, duration: 2000, icon: 'none'
                });
                return;
            }
            //获得当前编辑数据的ID
            let btnConf=btn.conf;
            let parameter="";
            let token = TokenUtil.getToken();
            for (let item of btnConf.params) {
                if (item.returnValue){
                    if (item.valueSource=="param"){
                        //表单字段映射
                        let paramName=item.returnValue;
                        paramName=paramName.toLowerCase();
                        parameter+= '&'+item.bindFieldLabel + '=' + json[paramName] ;
                    }else if (item.valueSource=="constantlet "){
                        //常量
                        let paramMap=[]
                        paramMap.push({name:item.bindFieldLabel,valueSource:item.valueSource,valueDef:item.returnValue})
                        //调用方法替换常量值
                        let rtn=await PublicApi.getParams(JSON.stringify(paramMap))
                        if (rtn){
                            parameter+= '&'+item.bindFieldLabel + '=' + rtn[item.bindFieldLabel] ;
                        }
                    }else if (item.valueSource=="fixedlet "){
                        //固定值
                        parameter+= '&'+item.bindFieldLabel + '=' + item.returnValue ;
                    }else {
                        parameter+="";
                    }
                }

            }

            let baseUrl_1 = "/ureport/preview?_u=qiaolin-" + btnConf.name + "&accessToken=" + token ;
            let mobileAppId = uni.getStorageSync("mobileAppId");
            if(mobileAppId){
                baseUrl_1 += "&mobileAppId=" + mobileAppId;
            }
            let baseUrl = baseUrl_1 += "&Id=" + json.ID_+parameter;
            let wPath = window.document.location.origin;
            let ureportPreviewUrl = wPath + baseUrl;
            let url = '/pages/RxIframe/RxIframe?url=' + baseUrl_1+'&title='+btn.name;
            uni.setStorageSync('ureportPreviewUrl',ureportPreviewUrl)
            uni.navigateTo({
                url: url
            })
        },
        //保存提交表单
        async submit() {
            let formSolution = this.resForm.formSolution;
            let action = 'save';
            let params = {
                data: this.rxForms.data,//表单数据
                setting: {
                    action: action,
                    alias: formSolution.alias
                }
            }
            let validRequired = this.canStartFlow ? false : true;
            //校验信息
            await this.rxForms.formCheckRule(validRequired, action).then(res=>{
                if (!res.success) {
                    //校验不通过
                    this.buttonLoading = {
                        key:'',
                        loading:false,
                    }
                    uni.showToast({
                        title: res.msg, duration: 2000, icon: 'none'
                    });
                    return
                }
                this.doSubmit(params)
            });
        },
        /*
        启动流程
         */
        async startFlow(btn) {
            let action = "start";
            var self_ = this;
            let formBuild = self_.getFormVm();
            let formData = formBuild.data;
            //清除字段前后空格；
            Util.removeSpaces(formData);
            var params = {
                flowDefMapping: self_.formSolution.flowDefMapping,
                formJson: formData
            }
            var flowDefRes = await FormSolutionApi.getFlowDefId(params);
            var flowDefId = flowDefRes.data;
            if (!flowDefId) {
                this.buttonLoading = {
                    key:'',
                    loading:false,
                }
                uni.showToast({
                    title:this.i18n('startFlowTips','无满足条件的流程定义！'), duration: 2000, icon: 'none'
                });
                this.buttonLoading = {
                    key:'',
                    loading:false,
                }
                return;
            }
            var processConfigRes = await BpmInstApi.getProcessConfig(flowDefId);
            if (!processConfigRes.success) {
                this.buttonLoading = {
                    key:'',
                    loading:false,
                }
                uni.showToast({
                    title: processConfigRes.message, duration: 2000, icon: 'none'
                });
                return;
            }
            if (processConfigRes.data) {
                var config = Util.deepClone(self_.processConfig);
                self_.processConfig = Object.assign(config, processConfigRes.data);
                self_.handleProcessConfig(self_.processConfig);
            }
            //对表单数据进行校验
            let parity = await this.rxForms.formCheckRule(true,action);
            if (!parity.success) {
                this.buttonLoading = {
                    key:'',
                    loading:false,
                }
                //校验不通过
                uni.showToast({
                    title: parity.msg, duration: 2000, icon: 'none'
                });
                return
            }
            let formSolution = this.resForm.formSolution;
            let paramsData = {
                data: this.rxForms.data,
                setting: {
                    action: 'start',
                    alias: formSolution.alias
                }
            }
            if (self_.processConfig.startConfirm && !self_.needConfirmDlg) { //启动流程确认
                uni.showModal({
                    title:this.i18n('tipsInfo','提示信息'),
                    content:this.i18n('confirmStartFlow','确认启动流程吗？'),
                    success: function (res) {
                        if (res.confirm) {
                            self_.doSubmit(paramsData);
                        } else if (res.cancel) {
                            self_.buttonLoading = {
                                key:'',
                                loading:false,
                            }
                            console.log('用户点击取消');
                        }
                    }
                });
            } else if (self_.needConfirmDlg) { //是否确认
                this.buttonLoading = {
                    key:'',
                    loading:false,
                }
                let formJson = {};
                self_.$set(formJson, formSolution.alias, formData)
                let dataObj = {
                    formSolutionAlias: formSolution.alias,
                    processConfig: self_.processConfig,
                    defId: flowDefId,
                    formData: formJson,
                    instId: self_.flowInstId || formData.instId || formData.INST_ID_
                }
                let url = '/views/modules/bpm/task/BpmInstStartConfirm';
                uni.setStorageSync('BpmInstStartConfirm',JSON.stringify(dataObj))
                uni.navigateTo({url: url})
            } else {
                self_.doSubmit(paramsData);
            }
        },
        /**
         * 提交保存表单
         */
        async doSubmit(params) {
            //在提交之前执行进行验证返回验证结果信息;
            this.rxForms._beforeSubmit(params);
            let res = await FormApi.saveForm(params);
            this.buttonLoading = {
                key:'',
                loading:false,
            }
            if (res.success) {
                //提交成功给执行
                this.rxForms._afterSubmit(res, this.data, 'save');

                uni.showToast({
                    title: res.message, duration: 2000, icon: 'none'
                });
                if(this.isShowFormDialog){
                    this.dialogClose({action:"ok",data:params.data});
                    return;
                }
                //返回上一页
                this.clickNavLeft()
                uni.$emit('onRefresh');
            } else {
                uni.showToast({
                    title:this.i18n('saveFailed','保存失败'), duration: 2000, icon: 'none'
                });
            }
        },
        /*
        打开表单
         */
        async openSolutionForm(btn){
            let formBuild=this.getFormVm();
            let config=btn.config.openConfig;
            let data=formBuild.data;
            let initData=this.getInitData(config,data,formBuild);
            let self_ = this;
            let appId = Util.getAppId(self_)
            let params = {
                alias: btn.config.openConfig.formAlias,
                action: 'edit',
                jsonParams:initData,
                appId:appId
            }
            uni.setStorageSync('openFormParams',JSON.stringify(params))
            uni.navigateTo({
                url:'/views/modules/form/customForm/FormSolutionShow/FormSolutionComponent?appId='+appId
            })
        },
        /*
        打开表单
         */
        async openCustomList(btn){
            let config=btn.config;
            //获取当前表单的数据
            let formBuild=this.getFormVm();
            let formData = formBuild.data;
            let params=config.params
            let queryParams=[]
            let typeJson = {string: "S", int: "I", date: "D", float: "F"};
            for(let param of params){
                let srcField=param.srcField.toLowerCase();
                if(!srcField){
                    continue;
                }
                let tablePre = param.tablePre ? param.tablePre + "." : "";
                let type = typeJson[param.dataType] ? typeJson[param.dataType] : "S";
                let queryString = "Q_" + tablePre + param.destField + "_" + type + "_" + param.fieldOp;
                let tmp = queryString + "=" + formData[srcField];
                queryParams.push(tmp);
            }
            //获取数据权限
            let listConfig=JSON.parse(btn.config.listConfig);
            let conf = {
                data: {
                    alias: listConfig.alias,
                    pmtAlias:listConfig.pmtAlias,
                    single: false,
                    params: queryParams,
                },
                curVm: this,
            };
            Dialog.openDialog(conf);
        },
        /**
         * 获取绑定值
         * @param (Object) data 当前表单数据
         * @param (String) curField 当前字段
         * @param (String) bindType 绑定类型
         * @param (Object) formVm 表单vm
         * @returns (Object) 绑定的数据.
         */
        getBindValue(data,curField,bindType,formVm){
            let type = bindType || "field";
            if(type=="field"){
                return data[curField];
            }
            if(type=="fixed"){
                return curField;
            }
            if(type=="script"){
                if(!curField){
                    console.info("form method is empty");
                    return "";
                }
                if(!formVm[curField]){
                    console.info("form method is not defined,please add ["+ curField +"]");
                    return "";
                }
                return formVm[curField](data);
            }
        },
        /**
         * 根据配置 构建映射初始化数据
         * @param (Object) config 配置
         * @param data 当前表单数据
         * @returns (Object) 初始化数据
         */
        getInitData(config,data,formVm){
            let formData={};
            if(!config.formConfig){
                return formData;
            }
            //根据配置 构建映射数据
            let formConfig=JSON.parse(config.formConfig);
            //遍历表配置
            for (let i = 0; i < formConfig.length; i++) {
                let obj=formConfig[i];
                if(!obj.fieldConfig || obj.fieldConfig.length==0){
                    continue;
                }
                //目标表类型
                let targetType= obj.targetType;
                //遍历字段配置
                for (let j = 0; j < obj.fieldConfig.length; j++) {
                    let fieldConfig=obj.fieldConfig[j];
                    let fieldCurType=fieldConfig.curType;
                    let targetField =fieldConfig.targetField;
                    let curTable = "sub__"+fieldConfig.curTable;
                    let curField = fieldConfig.curField;
                    let bindType = fieldConfig.bindType || "field";
                    let targetTable= "sub__"+obj.targetTable;
                    let targetTableName = obj.targetTable;
                    //映射到主表
                    if(targetType=="main"){
                        //当前主表
                        if(fieldCurType=="main"){
                            let val=this.getBindValue(data,curField,bindType,formVm);
                            formData[targetField]=val;
                        }else  if(fieldCurType=="onetoone"){ //当前一对一子表
                            let val=this.getBindValue(data[curTable],curField,bindType,formVm);
                            formData[targetField]=val;
                        }

                    }else if(obj.targetType=="onetoone"){//映射到一对一子表
                        //一对一子表无数据时默认{}
                        formData[targetTable] = formData[targetTable] || {};
                        //当前主表
                        if(fieldConfig.curType=="main"){
                            let val=this.getBindValue(data,curField,bindType,formVm);
                            formData[targetTable][targetField]=val;
                        }else  if(fieldConfig.curType=="onetoone"){ //当前一对一子表
                            let val=this.getBindValue(data[curTable],curField,bindType,formVm);
                            formData[targetTable][targetField]=val;
                        }
                    }else if(obj.targetType=="onetomany") {//映射到一对多子表
                        formData[targetTable] = formData[targetTable] || [];
                        formData.initData = formData.initData || {};
                        //子表初始化数据
                        formData.initData[targetTableName]=formData.initData[obj.targetTable] || {};
                        //当前主表
                        if(fieldConfig.curType=="main"){
                            formData.initData[targetTableName][targetField]=data[curField];
                            let tableData=formData[targetTable];
                            if(tableData && tableData.length>0){
                                for (let k = 0; k < tableData.length; k++) {
                                    let val=this.getBindValue(data,curField,bindType,formVm);
                                    tableData[k][targetField]=val;
                                }
                            }
                        }else  if(fieldConfig.curType=="onetoone"){ //当前一对一子表
                            formData.initData[targetTableName][targetField]=data[curTable][curField];
                            let tableData=formData[targetTable];
                            if(tableData && tableData.length>0){
                                for (let k = 0; k < tableData.length; k++) {
                                    let val=this.getBindValue(data[curTable],curField,bindType,formVm);
                                    tableData[k][targetField]=val;
                                }
                            }
                        }else {//当前一对多子表
                            if(!data[curTable]){
                                continue;
                            }
                            let curTableData =data[curTable];
                            for (let k = 0; k < curTableData.length; k++) {
                                let row=curTableData[k];
                                let val=this.getBindValue(row,curField,bindType,formVm);
                                //一对多子表单行无数据时默认{}
                                if(!formData[targetTable][k]){
                                    let subRow=JSON.parse(JSON.stringify(formData.initData[targetTableName]));
                                    subRow[targetField]= val;
                                    formData[targetTable][k]=subRow;
                                }else {
                                    formData[targetTable][k][targetField]=val;
                                }
                            }
                        }
                    }
                }
            }
            return formData;
        },
        handleProcessConfig(newVal) {
            let fillOpinion = false;
            let assignFlowUsers = false;
            let startCalFlowusers = false;
            //允许选择路径
            let allowSelectPath = newVal.allowSelectPath;
            let assignBatchFlowUsers = newVal.assignBatchFlowUsers;
            var startOptions = newVal.startNodeOptions;

            if (startOptions instanceof Array) {
                this.processConfig.startConfirm = startOptions.indexOf('startConfirm') != -1;
                fillOpinion = startOptions.indexOf('fillOpinion') != -1;
                assignFlowUsers = startOptions.indexOf('assignFlowUsers') != -1;
                startCalFlowusers = startOptions.indexOf('startCalFlowusers') != -1;
            }
            if (assignBatchFlowUsers || fillOpinion || assignFlowUsers || startCalFlowusers || allowSelectPath) {//需要显示弹出对话框
                this.needConfirmDlg = true;
            }
        },
        /**
         * 打开流程图
         */
        flowImage(btn){
            let formBuild=this.getFormVm();
            let formData = formBuild.data;
            let formGetData = formBuild.getData();
            let conf = {
                data: {
                    defId: this.flowDefId,
                    instId: this.flowInstId || formData.instId || formData.INST_ID_,
                    formData:formGetData,
                    dialogOptions:{
                        title:this.i18n('bpmImage','流程图'),
                        okText:''
                    },
                },
                curVm: this,
            };
            Dialog.openBpmImageView(conf, function (obj) {
            })
        },
        openUrl(com,destroy){
            if(com.url){
                let url = '/pages/RxIframe/RxIframe?url=' + com.url+'&title='+com.title;
                uni.navigateTo({
                    url: url
                })
            }
            destroy()
        },
        /**
         * 处理规则引擎.
         * @param btn
         */
        handleLiteFlow(btn){
            //获取当前表单的数据
            let formBuild=this.getFormVm();
            let data = formBuild.data;
            let config=btn.config;
            if(!config || !config.liteFlowId){
                this.$message.warning(this.i18n('liteFlowMessage','未绑定规则引擎!'));
                return;
            }
            let formData = {}
            formData[this.resForm.alias] = data ;
            FormApi.executeLiteFlow(config.liteFlowId,{formData:formData}).then(res=>{
                if(res.success){
                    uni.showToast({
                        title: res.message, // 消息内容
                        duration: 2000, // 持续时间（单位：毫秒）
                        icon: 'none' // 图标类型（可选值：success/loading/none）
                    });
                }
            });
        },
        /**
         * 复制添加
         * @param btn
         * @returns {Promise<void>}
         */
        async newSubmit(btn){
            let action="newSave";
            var validRequired = this.canStartFlow ? false : true;
            let formBuild=this.getFormVm();
            let validResult= {success:true,msg:""};
            try{
                validResult= await formBuild.formCheckRule(validRequired,action)
            }
            catch (e){
                validResult= e;
            }
            if (!validResult.success) {
                btn.loading=false;
                this.$message.warning(validResult.msg);
                return;
            }
            let paramsData = {
                data: formBuild.data,
                setting: {
                    action:action,
                    alias: this.resForm.alias
                }
            }
            this.doSubmit(paramsData)
        },
        /*
        审批历史
         */
        approvalHistory(btn){
            let formBuild=this.getFormVm();
            let formData = formBuild.data;
            let instId = this.flowInstId || formData.instId || formData.INST_ID_;
            let appId = Util.getAppId(this)
            uni.navigateTo({
                url: '/views/modules/bpm/task/BpmApprovalHistory?instId=' + instId + '&appId=' + appId
            })
        },
        edit(){
            this.action = 'edit';
            this.init(this.params)
        }
    }
}
